package com.wukang.photovoltaicinspectionpictures.ui.photograph

import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.wukang.photovoltaicinspectionpictures.R
import com.wukang.photovoltaicinspectionpictures.base.BaseActivity
import com.wukang.photovoltaicinspectionpictures.databinding.ActivityTakePhotographBinding
import com.wukang.photovoltaicinspectionpictures.logger.Rog
import com.wukang.photovoltaicinspectionpictures.ui.UiConstants
import com.wukang.photovoltaicinspectionpictures.utils.onDebounceClick
import kotlinx.coroutines.launch


/**
 * 拍照界面
 * @author wukang
 */
class TakePhotographActivity : BaseActivity<ActivityTakePhotographBinding, TakePhotographViewModel>() {
    private var mFragment: Fragment? = null

    override fun initViewBinding(): ActivityTakePhotographBinding = ActivityTakePhotographBinding.inflate(layoutInflater)

    override fun initViewModel(): TakePhotographViewModel = ViewModelProvider(this)[TakePhotographViewModel::class.java]

    override fun initActivity() {
        lifecycleScope.launch {
            mModel.switchFragmentState.collect {
                when (it) {
                    UiConstants.FRAGMENT_SHOW_PHOTOGRAPH -> switchFragment(ShowPhotographFragment.instance)
                    UiConstants.FRAGMENT_SEND_PHOTOGRAPH -> switchFragment(SendPhotographFragment.instance)
                    UiConstants.FRAGMENT_PHOTOGRAPH_RESULT -> switchFragment(PhotographResultFragment.instance)
                }
            }
        }
        // 第一个界面
        switchFragment(ShowPhotographFragment.instance)

    }

    override fun ActivityTakePhotographBinding.initView() {
        ivBack.onDebounceClick { finish() }
    }

    private fun switchFragment(fragment: Fragment) {
        // 判断当前显示的Fragment是不是切换的Fragment
        if (mFragment != fragment) {
            Rog.d(msg = "切换fragment，旧\"${mFragment.toString()}\" —> 新\"$fragment\"")
            supportFragmentManager.beginTransaction().replace(R.id.fl_container, fragment).commit()
            mFragment = fragment
        }
    }
}